package com.fingard.dsp.bank.directbank.jrtt02;

import com.bytedance.ea.bankconnector.api.AccountQueryService;
import com.bytedance.ea.bankconnector.api.dto.AccountDetailDto;
import com.bytedance.ea.bankconnector.api.dto.AccountQueryReq;
import com.bytedance.ea.bankconnector.api.dto.AccountQueryRsp;
import com.bytedance.ea.bankconnector.api.dto.BankBaseReq;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 财经-海外接口
 */
public class JRTT02Transaction extends JRTT02Base implements ITransaction {

    /**
     * 历史明细
     *
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //增加历史明细支持查询日期
        if (com.fingard.text.StringHelper.hasAnyChar(getBankConfig().getValueAsString("hisTransSupDate"))
                && getBankConfig().getValueAsString("hisTransSupDate").length() == 8) {
            //判断起始日
            Date avaiDate = Format.Date8Format.parse(getBankConfig().getValueAsString("hisTransSupDate"));
            Date startDate = Format.Date8Format.parse(p_req7516.dateFrom);
            Date endDate = Format.Date8Format.parse(p_req7516.dateTo);
            if (endDate.after(avaiDate)) {
                if (startDate.before(avaiDate)) {
                    p_req7516.dateFrom = getBankConfig().getValueAsString("hisTransSupDate");
                }
            } else {
                p_req7516.dateFrom = getBankConfig().getValueAsString("hisTransSupDate");
                p_req7516.dateTo = getBankConfig().getValueAsString("hisTransSupDate");
            }
        }
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            //明细按月查询，有些银行不支持跨月查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {//起始日期月份小于结束日期月份，表示跨月
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));//获取月末日期
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //BaseReq
                BankBaseReq ruleBaseReq = writeBankBaseReq(new JRTT02Header());
                //AccountQueryReq
                AccountQueryReq accountQueryReq = new AccountQueryReq();
                accountQueryReq.setQueryType("NTRYH");//历史明细
                accountQueryReq.setBankType(p_req7516.bankType);//银行体系
                accountQueryReq.setPayAccount(p_req7516.actNum);//付款帐号
                accountQueryReq.setPayIban(p_req7516.payIBAN);//付款IBAN账号
                accountQueryReq.setFrDt(Format.Date10Format.format(tmpCalendarFrom.getTime()));//该日期为账户时区的当日日期
                accountQueryReq.setToDt(Format.Date10Format.format(tmpClndrStepTo.getTime()));//该日期为输入日期
                accountQueryReq.setTimeZone(p_req7516.timeZone);//时差
                accountQueryReq.setBaseReq(ruleBaseReq);
                //Client
                DubboBeanFactory beanFactory = new DubboBeanFactory(bankFront, getBankConfig());
                AccountQueryService.Iface accountClient = beanFactory.getAccountService();
                WriteBankLogStep2("AccountQueryReq：" + accountQueryReq);
                AccountQueryRsp accountQueryRsp = accountClient.execute(accountQueryReq);
                WriteBankLogStep3("AccountQueryRsp：" + accountQueryRsp);
                //处理响应报文
                if (accountQueryRsp.getBaseRsp() != null) {
                    String respCode = accountQueryRsp.getBaseRsp().getResponseStatus();//返回码
                    String respInfo = accountQueryRsp.getBaseRsp().getAddtlInf();//返回信息
                    if ("ACCP".equals(respCode)) {
                        List<AccountDetailDto> accountDetailDtoList = accountQueryRsp.getDetailList();
                        if (accountDetailDtoList != null && accountDetailDtoList.size() > 0) {
                            for (AccountDetailDto accountDetailDto : accountDetailDtoList) {
                                if (accountDetailDto.getBookgDate() == null || accountDetailDto.getValueDate() == null
                                        || accountDetailDto.getDcFlag() == null || accountDetailDto.getCurrency() == null) {
                                    retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
                                    retAtsTrans.writeStart();//写返回ATS的统一头部信息
                                    retAtsTrans.writeRespCode("-1");
                                    retAtsTrans.writeRespInfo("明细" + accountDetailDto.toString() + "中交易日期、起息日期、借贷标识、币种存在为空的数据");
                                    retAtsTrans.writeEnd();
                                    return retAtsTrans;
                                }
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                detail.actArea = p_req7516.actArea;//账户区域
                                detail.actNum = p_req7516.actNum;//银行账号
                                detail.tranDate = DateHelper.convertD8toD10(accountDetailDto.getBookgDate());//交易日期
                                detail.tranTime = detail.tranDate + " 00:00:00";//交易时间
                                detail.valueDate = DateHelper.convertD8toD10(accountDetailDto.getValueDate());//起息日
                                String payamt = amountChange(accountDetailDto.getTransAmount());//交易金额
                                String cdFlag = accountDetailDto.getDcFlag();//借贷标识
                                if ("RD".equals(cdFlag) || "C".equals(cdFlag)) {
                                    if (payamt.contains("-")) {
                                        detail.tranAmt = payamt.substring(1);
                                        detail.cdFlag = "1";
                                    } else {
                                        detail.tranAmt = payamt;
                                        detail.cdFlag = "2";
                                    }
                                } else if ("RC".equals(cdFlag) || "D".equals(cdFlag)) {
                                    if (payamt.contains("-")) {
                                        detail.tranAmt = payamt.substring(1);
                                        detail.cdFlag = "2";
                                    } else {
                                        detail.tranAmt = payamt;
                                        detail.cdFlag = "1";
                                    }
                                }
                                if (accountDetailDto.getAddtlTxInf() != null) {
                                    detail.accBal = accountDetailDto.getAddtlTxInf();//账户余额
                                }
                                detail.busType = accountDetailDto.getBkTransDesc();//摘要
                                detail.abstr = "";//对账码
                                detail.cur = convertCurToATS(accountDetailDto.getCurrency());//币种
                                detail.askNumber = accountDetailDto.getEndToEndId();
                                detail.originator = detail.askNumber;
                                detail.comment = accountDetailDto.getAddtlNtryInf();
                                detail.payCode = accountDetailDto.getPurpose();
                                String inTransDate = getBankConfig().getSetValue("inTransDate", "", p_req7516.reqHeader.transType);
                                if (com.fingard.text.StringHelper.hasAnyChar(inTransDate) && inTransDate.length() == 8) {
                                    //判断起始日
                                    Date avaiDate = Format.Date8Format.parse(inTransDate);//生效时间
                                    Date tranDate = Format.Date8Format.parse(DateHelper.convertD10toD8(detail.tranDate));//交易时间
                                    if (!tranDate.before(avaiDate)) {
                                        //生效，增加节点
                                        detail.uniqueID = p_req7516.actNum + "-" + accountDetailDto.getTxId();//防重标识
                                    }
                                }
                                //解析86字段
                                if ("1".equals(getBankConfig().getValueAsString("tag86PlayFlag"))) {
                                    Map<String, String> map = resolveTag86(detail.comment, detail.cdFlag, false);
                                    if (map.size() > 0) {
                                        detail.recAccNum = StringHelper.isNullOrEmpty(map.get("RecAccNum")) ? "" : map.get("RecAccNum");//收方银行账号
                                        detail.recAccName = StringHelper.isNullOrEmpty(map.get("RecAccName")) ? "" : map.get("RecAccName");//收方账户名称
                                        detail.recAccBank = StringHelper.isNullOrEmpty(map.get("RecAccBannk")) ? "" : map.get("RecAccBannk");//收方银行名称
                                        detail.usage = StringHelper.isNullOrEmpty(map.get("Usage")) ? "" : map.get("Usage");//用途
                                    }
                                } else {
                                    detail.recAccNum = accountDetailDto.getDescDetails().opAccountId;//收方银行账号
                                    detail.recAccName = accountDetailDto.getDescDetails().opAccountName;//收方账户名称
                                    detail.recAccBank = accountDetailDto.getDescDetails().opBankName;//收方银行名称
                                    detail.usage = accountDetailDto.getDescDetails().paymentDetails;//用途
                                    detail.originator=accountDetailDto.getDescDetails().getReference();
                                }
                                retAtsTrans.writeRetDetail(detail);
                            }
                        }
                    } else {//查询异常
                        tmpRespCode = "-1";
                        tmpRespInfo = respInfo;
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = "响应BaseRsp为空";
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//月末后一天日期
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     *
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7515.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //查询时间日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.DateTimeFormat.parse(Format.DateTimeFormat.format(new Date())));
            //拼接报文
            //BaseReq
            BankBaseReq ruleBaseReq = writeBankBaseReq(new JRTT02Header());
            //AccountQueryReq
            AccountQueryReq accountQueryReq = new AccountQueryReq();
            accountQueryReq.setQueryType("NTRYI");//历史明细
            accountQueryReq.setBankType(p_req7515.bankType);//银行体系
            accountQueryReq.setPayAccount(p_req7515.actNum);//付款帐号
            accountQueryReq.setPayIban(p_req7515.payIBAN);//付款IBAN账号
            accountQueryReq.setFrDt(getGlobalLocalDate(tmpCalendarFrom.getTime(), p_req7515.timeZone));//该日期为账户时区的当日日期
            accountQueryReq.setToDt(Format.Date10Format.format(tmpCalendarFrom.getTime()));//该日期为输入日期
            accountQueryReq.setTimeZone(p_req7515.timeZone);//时差
            accountQueryReq.setBaseReq(ruleBaseReq);
            //Client
            DubboBeanFactory beanFactory = new DubboBeanFactory(bankFront, getBankConfig());
            AccountQueryService.Iface accountClient = beanFactory.getAccountService();
            WriteBankLogStep2("AccountQueryReq：" + accountQueryReq);
            AccountQueryRsp accountQueryRsp = accountClient.execute(accountQueryReq);
            WriteBankLogStep3("AccountQueryRsp：" + accountQueryRsp);
            //处理响应报文
            if (accountQueryRsp.getBaseRsp() != null) {
                String respCode = accountQueryRsp.getBaseRsp().getResponseStatus();//返回码
                String respInfo = accountQueryRsp.getBaseRsp().getAddtlInf();//返回信息
                if ("ACCP".equals(respCode)) {
                    List<AccountDetailDto> accountDetailDtoList = accountQueryRsp.getDetailList();
                    if (accountDetailDtoList != null && accountDetailDtoList.size() > 0) {
                        for (AccountDetailDto accountDetailDto : accountQueryRsp.getDetailList()) {
                            if (accountDetailDto.getBookgDate() == null || accountDetailDto.getValueDate() == null
                                    || accountDetailDto.getDcFlag() == null || accountDetailDto.getCurrency() == null) {
                                retAtsTrans = new RetAtsTrans(p_req7515.reqHeader);
                                retAtsTrans.writeStart();//写返回ATS的统一头部信息
                                retAtsTrans.writeRespCode("-1");
                                retAtsTrans.writeRespInfo("明细" + accountDetailDto.toString() + "中交易日期、起息日期、借贷标识、币种存在为空的数据");
                                retAtsTrans.writeEnd();
                                return retAtsTrans;
                            }
                            RetAtsTransDetail detail = new RetAtsTransDetail();
                            detail.actArea = p_req7515.actArea;//账户区域
                            detail.actNum = p_req7515.actNum;//银行账号
                            detail.valueDate = DateHelper.convertD8toD10(accountDetailDto.getValueDate());//起息日
                            detail.tranDate = DateHelper.convertD8toD10(accountDetailDto.getBookgDate());//交易日期
                            detail.tranTime = detail.tranDate + " 00:00:00";//交易时间
                            String payamt = amountChange(accountDetailDto.getTransAmount());//交易金额
                            String cdFlag = accountDetailDto.getDcFlag();//借贷标识
                            if ("RD".equals(cdFlag) || "C".equals(cdFlag)) {
                                if (payamt.contains("-")) {
                                    detail.tranAmt = payamt.substring(1);
                                    detail.cdFlag = "1";
                                } else {
                                    detail.tranAmt = payamt;
                                    detail.cdFlag = "2";
                                }
                            } else if ("RC".equals(cdFlag) || "D".equals(cdFlag)) {
                                if (payamt.contains("-")) {
                                    detail.tranAmt = payamt.substring(1);
                                    detail.cdFlag = "2";
                                } else {
                                    detail.cdFlag = "1";
                                    detail.tranAmt = payamt;
                                }
                            }
                            if (accountDetailDto.getAddtlTxInf() != null) {
                                detail.accBal = accountDetailDto.getAddtlTxInf();//账户余额
                            }
                            detail.busType = accountDetailDto.getBkTransDesc();//摘要
                            detail.abstr = "";//对账码
                            detail.cur = convertCurToATS(accountDetailDto.getCurrency());//币种
                            detail.askNumber = accountDetailDto.getEndToEndId();
                            detail.originator = accountDetailDto.getTxId();
                            detail.comment = accountDetailDto.getAddtlNtryInf();
                            detail.payCode = accountDetailDto.getPurpose();
                            String inTransDate = getBankConfig().getSetValue("inTransDate", "", p_req7515.reqHeader.transType);
                            if (com.fingard.text.StringHelper.hasAnyChar(inTransDate) && inTransDate.length() == 8) {
                                //判断起始日
                                Date avaiDate = Format.Date8Format.parse(inTransDate);//生效时间
                                Date tranDate = Format.Date8Format.parse(DateHelper.convertD10toD8(detail.tranDate));//交易时间
                                if (!tranDate.before(avaiDate)) {
                                    //生效，增加节点
                                    detail.uniqueID = p_req7515.actNum + "-" + accountDetailDto.getTxId();//防重标识
                                }
                            }
                            //解析86字段
                            if ("1".equals(getBankConfig().getValueAsString("tag86PlayFlag"))) {
                                Map<String, String> map = resolveTag86(detail.comment, detail.cdFlag, true);
                                if (map.size() > 0) {
                                    detail.recAccNum = StringHelper.isNullOrEmpty(map.get("RecAccNum")) ? "" : map.get("RecAccNum");//收方银行账号
                                    detail.recAccName = StringHelper.isNullOrEmpty(map.get("RecAccName")) ? "" : map.get("RecAccName");//收方账户名称
                                    detail.recAccBank = StringHelper.isNullOrEmpty(map.get("RecAccBannk")) ? "" : map.get("RecAccBannk");//收方银行名称
                                    detail.usage = StringHelper.isNullOrEmpty(map.get("Usage")) ? "" : map.get("Usage");//用途
                                }
                            } else {
                                detail.recAccNum = accountDetailDto.getDescDetails().opAccountId;//收方银行账号
                                detail.recAccName = accountDetailDto.getDescDetails().opAccountName;//收方账户名称
                                detail.recAccBank = accountDetailDto.getDescDetails().opBankName;//收方银行名称
                                detail.usage = accountDetailDto.getDescDetails().paymentDetails;//用途
                                detail.originator=accountDetailDto.getDescDetails().getReference();
                            }
                            retAtsTrans.writeRetDetail(detail);
                        }
                    }
                } else {//查询异常
                    tmpRespCode = "-1";
                    tmpRespInfo = respInfo;
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "响应BaseRsp为空";
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7515.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }
}
